package com.ruoyi.web.controller.test;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.socket.config.BinanceProxyConfig;
import com.ruoyi.websocket.BinanceWebSocketProxyConfig;
import com.ruoyi.websocket.SystemProxyManager;
import com.ruoyi.websocket.WebSocketRunner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统代理测试控制器
 * 增强版：支持币安专用代理配置测试
 */
@RestController
@RequestMapping("/test/system-proxy")
@Slf4j
public class SystemProxyTestController {
    
    @Resource
    private SystemProxyManager systemProxyManager;
    
    @Resource
    private BinanceProxyConfig binanceProxyConfig;
    
    @Resource
    private BinanceWebSocketProxyConfig binanceWebSocketProxyConfig;
    
    @Resource
    private WebSocketRunner webSocketRunner;
    
    /**
     * 查看代理状态（增强版）
     */
    @GetMapping("/status")
    public AjaxResult getProxyStatus() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 系统代理状态
            result.put("systemProxyEnabled", systemProxyManager.isProxyEnabled());
            result.put("systemProxyInfo", systemProxyManager.getCurrentProxyInfo());
            
            // 币安代理状态
            result.put("binanceProxyInfo", binanceWebSocketProxyConfig.getProxyInfo());
            
            // 配置状态
            result.put("configValid", binanceProxyConfig.isValidConfig());
            result.put("currentUsername", binanceProxyConfig.getCurrentUsername());
            result.put("randomExpired", binanceProxyConfig.isRandomExpired());
            result.put("websocketStatus", systemProxyManager.getWebSocketStatus());
            
            // 系统属性状态
            Map<String, String> systemProps = new HashMap<>();
            systemProps.put("http.proxyHost", System.getProperty("http.proxyHost"));
            systemProps.put("http.proxyPort", System.getProperty("http.proxyPort"));
            systemProps.put("http.proxyUser", System.getProperty("http.proxyUser"));
            systemProps.put("https.proxyHost", System.getProperty("https.proxyHost"));
            systemProps.put("https.proxyPort", System.getProperty("https.proxyPort"));
            systemProps.put("https.proxyUser", System.getProperty("https.proxyUser"));
            systemProps.put("jdk.http.auth.tunneling.disabledSchemes", 
                    System.getProperty("jdk.http.auth.tunneling.disabledSchemes"));
            result.put("systemProperties", systemProps);
            
            return AjaxResult.success("代理状态查询成功", result);
        } catch (Exception e) {
            log.error("查询代理状态失败", e);
            return AjaxResult.error("查询代理状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 启用系统代理（增强版）
     */
    @PostMapping("/enable")
    public AjaxResult enableProxy() {
        try {
            // 启用币安专用代理
            binanceWebSocketProxyConfig.configureBinanceWebSocketProxy();
            
            // 启用系统代理
            systemProxyManager.enableSystemProxy();
            
            Map<String, Object> result = new HashMap<>();
            result.put("systemProxyInfo", systemProxyManager.getCurrentProxyInfo());
            result.put("binanceProxyInfo", binanceWebSocketProxyConfig.getProxyInfo());
            
            return AjaxResult.success("代理已启用", result);
        } catch (Exception e) {
            log.error("启用代理失败", e);
            return AjaxResult.error("启用代理失败: " + e.getMessage());
        }
    }
    
    /**
     * 禁用系统代理
     */
    @PostMapping("/disable")
    public AjaxResult disableProxy() {
        try {
            systemProxyManager.disableSystemProxy();
            return AjaxResult.success("系统代理已禁用");
        } catch (Exception e) {
            log.error("禁用系统代理失败", e);
            return AjaxResult.error("禁用系统代理失败: " + e.getMessage());
        }
    }
    
    /**
     * 刷新代理配置（增强版）
     */
    @PostMapping("/refresh")
    public AjaxResult refreshProxy() {
        try {
            // 刷新币安代理
            binanceWebSocketProxyConfig.refreshProxyAuth();
            
            // 刷新系统代理
            systemProxyManager.refreshProxyConfig();
            
            Map<String, Object> result = new HashMap<>();
            result.put("systemProxyInfo", systemProxyManager.getCurrentProxyInfo());
            result.put("binanceProxyInfo", binanceWebSocketProxyConfig.getProxyInfo());
            
            return AjaxResult.success("代理配置已刷新", result);
        } catch (Exception e) {
            log.error("刷新代理配置失败", e);
            return AjaxResult.error("刷新代理配置失败: " + e.getMessage());
        }
    }
    
    /**
     * 强制刷新代理配置（增强版）
     */
    @PostMapping("/force-refresh")
    public AjaxResult forceRefreshProxy() {
        try {
            // 强制刷新币安代理
            binanceProxyConfig.generateNewRandom();
            binanceWebSocketProxyConfig.configureBinanceWebSocketProxy();
            
            // 强制刷新系统代理
            systemProxyManager.forceRefreshProxyConfig();
            
            Map<String, Object> result = new HashMap<>();
            result.put("systemProxyInfo", systemProxyManager.getCurrentProxyInfo());
            result.put("binanceProxyInfo", binanceWebSocketProxyConfig.getProxyInfo());
            result.put("newUsername", binanceProxyConfig.getCurrentUsername());
            
            return AjaxResult.success("代理配置已强制刷新", result);
        } catch (Exception e) {
            log.error("强制刷新代理配置失败", e);
            return AjaxResult.error("强制刷新代理配置失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试代理连接（增强版）
     */
    @GetMapping("/test")
    public AjaxResult testProxy() {
        try {
            boolean systemProxyTest = systemProxyManager.testProxyConnection();
            
            Map<String, Object> result = new HashMap<>();
            result.put("systemProxyTest", systemProxyTest);
            result.put("systemProxyInfo", systemProxyManager.getCurrentProxyInfo());
            result.put("binanceProxyInfo", binanceWebSocketProxyConfig.getProxyInfo());
            
            if (systemProxyTest) {
                return AjaxResult.success("代理连接测试成功", result);
            } else {
                return AjaxResult.error("代理连接测试失败", result);
            }
        } catch (Exception e) {
            log.error("测试代理连接失败", e);
            return AjaxResult.error("测试代理连接失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试币安API连接
     */
    @GetMapping("/test-binance")
    public AjaxResult testBinanceConnection() {
        try {
            // 配置币安代理
            binanceWebSocketProxyConfig.configureBinanceWebSocketProxy();
            
            // 测试连接
            boolean success = systemProxyManager.testProxyConnection();
            
            Map<String, Object> result = new HashMap<>();
            result.put("testResult", success);
            result.put("binanceProxyInfo", binanceWebSocketProxyConfig.getProxyInfo());
            result.put("systemProperties", getRelevantSystemProperties());
            
            if (success) {
                return AjaxResult.success("币安API连接测试成功", result);
            } else {
                return AjaxResult.error("币安API连接测试失败", result);
            }
        } catch (Exception e) {
            log.error("测试币安连接失败", e);
            return AjaxResult.error("测试币安连接失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取WebSocket状态
     */
    @GetMapping("/websocket-status")
    public AjaxResult getWebSocketStatus() {
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("websocketStatus", systemProxyManager.getWebSocketStatus());
            result.put("runnerMap", WebSocketRunner.getMap());
            result.put("binanceProxyInfo", binanceWebSocketProxyConfig.getProxyInfo());
            
            return AjaxResult.success("WebSocket状态查询成功", result);
        } catch (Exception e) {
            log.error("查询WebSocket状态失败", e);
            return AjaxResult.error("查询WebSocket状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 重启WebSocket连接
     */
    @PostMapping("/restart-websocket")
    public AjaxResult restartWebSocket() {
        try {
            webSocketRunner.reStart();
            return AjaxResult.success("WebSocket连接已重启");
        } catch (Exception e) {
            log.error("重启WebSocket连接失败", e);
            return AjaxResult.error("重启WebSocket连接失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取代理配置信息
     */
    @GetMapping("/config")
    public AjaxResult getProxyConfig() {
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("enabled", binanceProxyConfig.isEnabled());
            result.put("host", binanceProxyConfig.getHost());
            result.put("port", binanceProxyConfig.getPort());
            result.put("usernameTemplate", binanceProxyConfig.getUsernameTemplate());
            result.put("currentUsername", binanceProxyConfig.getCurrentUsername());
            result.put("timeout", binanceProxyConfig.getTimeout());
            result.put("validConfig", binanceProxyConfig.isValidConfig());
            result.put("randomExpired", binanceProxyConfig.isRandomExpired());
            result.put("binanceProxyInfo", binanceWebSocketProxyConfig.getProxyInfo());
            
            return AjaxResult.success("代理配置查询成功", result);
        } catch (Exception e) {
            log.error("查询代理配置失败", e);
            return AjaxResult.error("查询代理配置失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取相关系统属性
     */
    private Map<String, String> getRelevantSystemProperties() {
        Map<String, String> props = new HashMap<>();
        props.put("http.proxyHost", System.getProperty("http.proxyHost"));
        props.put("http.proxyPort", System.getProperty("http.proxyPort"));
        props.put("http.proxyUser", System.getProperty("http.proxyUser"));
        props.put("https.proxyHost", System.getProperty("https.proxyHost"));
        props.put("https.proxyPort", System.getProperty("https.proxyPort"));
        props.put("https.proxyUser", System.getProperty("https.proxyUser"));
        props.put("jdk.http.auth.tunneling.disabledSchemes", 
                System.getProperty("jdk.http.auth.tunneling.disabledSchemes"));
        return props;
    }
} 